import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/provider/UserInforModel.dart';
import 'package:flutter_juwo/provider/index_provider.dart';
import 'package:flutter_juwo/ui/custom/real_rich_text.dart';
import 'package:flutter_juwo/ui/custom/select_show_pic_widget.dart';
import 'package:flutter_juwo/ui/model/user_infor_entity.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/progress_view.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:provider/provider.dart';

import 'model/picadd_entity.dart';
import 'model/imperfect_entity.dart';

class PersonalCenter extends StatefulWidget {
  @override
  _PersonalCenterState createState() => _PersonalCenterState();
}

class _PersonalCenterState extends State<PersonalCenter>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  bool firstRefresh = true;
  UserInforEntity userInforEntity;
  EasyRefreshController _easyRefreshController = new EasyRefreshController();
  ImperfectEntity imperfectEntity;
  bool accountOk = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    if (SpUtil.getString(SpKeys.userToken) == "") {
      firstRefresh = false;
    }

    ///this.getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colours.c243,
      appBar: UiUtils.appHomeBar(context, "个人中心"),
      body: Column(
        children: <Widget>[
          UiUtils.divider(color: Colours.c243, height: 2),
          Expanded(
            flex: 1,
            child: Consumer<UserModel>(
              builder: (context, UserModel userModel, _) {
                if (userModel.value != "") {
                  _easyRefreshController.callRefresh();
                  userModel.updateToken("");
                }
                return EasyRefresh(
                    controller: _easyRefreshController,
                    firstRefresh: firstRefresh,
                    enableControlFinishRefresh: true,
                    enableControlFinishLoad: true,
                    header: BallPulseHeader(),
                    onRefresh: () async {
                      await Future.delayed(Duration(seconds: 1), () {
                        if (SpUtil.getString(SpKeys.userToken).isEmpty) {
                          ToastUtil.showShortToast("登录后方可查看");
                          _easyRefreshController.finishRefresh();
                          return;
                        }
                        this.getData();
                      });
                    },
                    child: ListView(
                      shrinkWrap: true,
                      children: <Widget>[
                        this.getTop(),
                        UiUtils.divider(height: 20),
                        this.getTasFun(),
                        UiUtils.divider(height: 20),
                        this.getBottomFun(userModel)
                      ],
                    ));
              },
            ),
          )
        ],
      ),
    );
  }

  ///用户基础信息、余额、金币等信息 y6686  推手
  getTop() {
    List<Widget> list = [];
    list.add(getUserInfo());

    ///1 是推手
    if (null != userInforEntity && userInforEntity.data.ts == "1") {
      list.add(getTs());
      list.add(UiUtils.divider(height: 20));
    }

    list.add(getMoneyInfo());

    return Container(
      color: Colors.white,
      child: Column(
        children: list,
      ),
    );
  }

  ///显示用户头像，手机号（去登陆、注册）
  getUserInfo() {
    ///未登录时显示
    if (null == userInforEntity) {
      return Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), 0, 0),
        child: Row(
          children: <Widget>[
            Container(
              height: ScreenUtil().setWidth(120),
              width: ScreenUtil().setWidth(120),
              child: ClipOval(
                child: CachedNetworkImage(
                  fit: BoxFit.fill,
                  imageUrl: '',
                  placeholder: (context, url) => new ProgressView(),
                  errorWidget: (context, url, error) => Image.asset(
                    Utils.getImgPath('icon_default_head'),
                    fit: BoxFit.fill,
                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                NavigatorUtils.push(context, Routes.login);
              },
              child: Container(
                margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
                child: RealRichText([
                  TextSpan(
                    text: "登录",
                    style: TextStyles.custom(
                        30, Colours.appC3, Font.PingFangRegular),
                  ),
                  TextSpan(
                    text: "/",
                    style: TextStyles.custom(
                        30, Colours.appC2, Font.PingFangRegular),
                  ),
                  TextSpan(
                    text: "注册",
                    style: TextStyles.custom(
                        30, Colours.appC3, Font.PingFangRegular),
                  )
                ]),
              ),
            )
          ],
        ),
      );
    }

    ///登录后显示
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), 0, 0),
      child: Row(
        children: <Widget>[
          Container(
            height: ScreenUtil().setWidth(120),
            width: ScreenUtil().setWidth(120),
            child: SelectShowPicWidget(1, (values) {
              userInforEntity.data.pic == null
                  ? picadd(values[0])
                  : picadd(values[1]);
            },
                imgUrls: userInforEntity.data.pic == null
                    ? []
                    : [userInforEntity.data.pic],
                isHead: true),
          ),
          Container(
            height: ScreenUtil().setWidth(120),
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  child: Text(
                    "${userInforEntity.data.tel}",
                    style: TextStyles.custom(
                        38, Colours.appC1, Font.PingFangBlod),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    ///跳转到会员中心
                    NavigatorUtils.push(context,
                        "${Routes.memberPage}?money=${userInforEntity.data.money}");
                  },
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil().setWidth(15),
                        ScreenUtil().setWidth(0),
                        ScreenUtil().setWidth(15),
                        ScreenUtil().setWidth(0)),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        border: Border.all(
                            color: Colours.appC11,
                            width: ScreenUtil().setWidth(1))),
                    child: Text(
                      "升级会员享更多特权",
                      style: TextStyles.custom(
                          30, Colours.appC11, Font.PingFangMedium),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  ///显示余额、金币相关
  getMoneyInfo() {
    return GridView.count(
      physics: new NeverScrollableScrollPhysics(),
      //增加
      shrinkWrap: true,
      padding: const EdgeInsets.all(8.0),
      primary: false,
      // 竖向间距
      mainAxisSpacing: 0,
      // 横向 Item 的个数
      crossAxisCount: 2,
      // 横向间距
      crossAxisSpacing: 0,
      childAspectRatio: 3,

      children: this.getFun1Items(),
    );
  }

  getFun1Items() {
    List<Widget> wigets = new List();
    wigets.add(Consumer<UserInforModel>(
      builder: (context, UserInforModel model, _) => Container(
        child: this.getMoneyInfoItem(Icons.attach_money,
            msg: "可用余额(元)",
            num: userInforEntity == null ? "0.00" : "${model.userMoneyValue}"),
      ),
    ));
    wigets.add(Consumer<UserInforModel>(
      builder: (context, UserInforModel model, _) => Container(
        child: this.getMoneyInfoItem(Icons.sync,
            msg: "可用金币(金)",
            num: userInforEntity == null ? "0.00" : "${model.userGoldValue}"),
      ),
    ));
    wigets.add(this.getMoneyInfoItem(Icons.money_off,
        msg: "待返余额(元)",
        num: userInforEntity == null
            ? "0.00"
            : "${userInforEntity.data.moneyFrozen}"));
    wigets.add(this.getMoneyInfoItem(Icons.sync_problem,
        msg: "待返金币(金)",
        num: userInforEntity == null
            ? "0.00"
            : "${userInforEntity.data.goldFrozen}"));
    return wigets;
  }

  Widget getMoneyInfoItem(IconData widgets,
      {String msg = "", String num = "0.00"}) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30), 0, ScreenUtil().setWidth(30), 0),
      child: GestureDetector(
        onTap: () {
          if (msg == "可用余额(元)") {
            NavigatorUtils.push(context, Routes.myMoney);
          }

          if (msg == "可用金币(金)") {
            NavigatorUtils.push(context, Routes.myGold);
          }

          if (msg == "待返余额(元)" || msg == "待返金币(金)") {
            NavigatorUtils.push(context, "${Routes.order}?index=0");

            ///  NavigatorUtils.push(context, Routes.waitReturn);
          }
        },
        child: Row(
          children: <Widget>[
            Container(
              child: Icon(
                widgets,
                color: Colors.black,
                size: 26,
              ),
              margin: EdgeInsets.only(right: ScreenUtil().setWidth(30)),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  "$num",
                  style: TextStyles.custom(
                      34, Colours.appC1, Font.PingFangRegular),
                ),
                msg == ""
                    ? Container()
                    : RealRichText([
                        TextSpan(
                            text: "$msg",
                            style: TextStyles.custom(24, Color(0xFFC0C0C0),
                                Font.PingFangRegular)),
                        ImageSpan(AssetImage(Utils.getImgPath("icon_right")),
                            imageWidth: 12, imageHeight: 12)
                      ])
              ],
            )
          ],
        ),
      ),
    );
  }

  ///显示任务步骤
  getTasFun() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30)),
      child: Column(
        children: <Widget>[
          InkWell(
            onTap: () {
              ///跳转到任务列表
              NavigatorUtils.push(context, "${Routes.order}?index=0");
            },
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(30), 0, ScreenUtil().setWidth(30), 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    "全部任务",
                    style: this.getTextStyle(),
                  ),
                  Image.asset(
                    Utils.getImgPath("icon_right"),
                    height: 14,
                    width: 14,
                  )
                ],
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(40)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                this.getTaskItem(
                  "进行中",
                  Icons.event,
                ),
                this.getTaskItem(
                  "待评价",
                  Icons.event_note,
                ),
                this.getTaskItem("已完成", Icons.event_available,
                    num: userInforEntity != null &&
                            userInforEntity.data.billFinishNum != "0"
                        ? "${userInforEntity.data.billFinishNum}"
                        : ""),
                this.getTaskItem("已失败", Icons.event_busy),
              ],
            ),
          )
        ],
      ),
    );
  }

  TextStyle getTextStyle() {
    return TextStyles.custom(32, Colours.appC1, Font.PingFangMedium);
  }

  getTaskItem(String s, IconData icon, {String num = ""}) {
    Paint pg = Paint();
    pg.style = PaintingStyle.fill;
    pg.color = Color(0x00000000);

    return InkWell(
      onTap: () {
        int index = getIndex(s);

        ///跳转到任务列表
        NavigatorUtils.push(context, "${Routes.order}?index=$index");
      },
      child: Column(
        children: <Widget>[
          Stack(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(10),
                    right: ScreenUtil().setWidth(10),
                    top: ScreenUtil().setWidth(10)),
                child: Icon(
                  icon,
                  color: Colors.grey[850],
                  size: 30,
                ),
              ),
              Positioned(
                right: 0,
                child: num == ""
                    ? Container()
                    : Container(
                        height: ScreenUtil().setWidth(36),
                        width: ScreenUtil().setWidth(36),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Colours.appC10, // 底色
                          borderRadius: new BorderRadius.circular(50), // 圆角度
                          //  borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 50)), // 也可控件一边圆角大小
                        ),
                        child: Text(
                          "$num",
                          style: TextStyles.custom(
                              24, Colours.white, Font.PingFangMedium),
                        ),
                      ),
              )
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
            child: Text(
              "$s",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangMedium),
            ),
          )
        ],
      ),
    );
  }

  getBottomFun(UserModel userModel) {
    List<Widget> list = [];
    list.add(this.getBottomFunItem("电商账号", userModel,
        msg: accountOk ? "" : imperfectEntity.data, isAccount: true));
    list.add(this.getBottomFunItem("会员等级", userModel, msg: "提前返款，优先接单"));
    if (null == userInforEntity || userInforEntity.data.ts != "1") {
      list.add(this.getBottomFunItem("推广赚钱", userModel, msg: "享10%永久分成收益"));
    }

    if (null != userInforEntity) {
      list.add(this.getBottomFunItem("修改密码", userModel, msg: ""));
      list.add(this.getBottomFunItem("我的申诉", userModel, msg: ""));
      list.add(this.getBottomFunItem("退出登录", userModel, msg: ""));
    }

    return Container(
      color: Colors.white,
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), 0),
      child: Column(
        children: list,
      ),
    );
  }

  getBottomFunItem(String name, UserModel userModel,
      {String msg = "", bool isAccount = false}) {
    return GestureDetector(
      onTap: () {
        if (name == "电商账号") {
          /// NavigatorUtils.push(context, Routes.userInfor);
          NavigatorUtils.push(context, "${Routes.taoList}?isFromTask=0");
        }

        if (name == "退出登录") {
          this.logOut(userModel);
        }

        if (name == "我的申诉") {
          NavigatorUtils.push(context, Routes.representationList);
        }
        if (name == "推广赚钱") {
          NavigatorUtils.push(context, Routes.share);
        }
        if (name == "会员等级") {
          NavigatorUtils.push(context,
              "${Routes.memberPage}?money=${userInforEntity.data.money}");
        }

        if (name == "我是推手（团队创始人）") {
          NavigatorUtils.push(context, "${Routes.ts}?index=0");
        }
        if (name == "修改密码") {
          NavigatorUtils.push(context, Routes.changePwd);
        }
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(0, 0, 0, ScreenUtil().setWidth(40)),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Text(
                "$name",
                style: this.getTextStyle(),
              ),
            ),
            msg == ""
                ? Container()
                : Text(
                    "$msg",
                    style: TextStyles.custom(
                        26,
                        isAccount ? Colours.appC16 : Colours.appC2,
                        Font.PingFangMedium),
                  ),
            Image.asset(
              Utils.getImgPath("icon_right"),
              height: ScreenUtil().setWidth(30),
              width: ScreenUtil().setWidth(30),
            )
          ],
        ),
      ),
    );
  }

  Future getData() async {
    DioManager.getInstance().get(Api.USER_INFOR, null, (json) {
      userInforEntity = UserInforEntity.fromJson(json);
      if (null == userInforEntity) {
        ///未登录
        ToastUtil.showShortToast("请从新登录");
        _easyRefreshController.finishRefresh();
        return;
      }

      if (userInforEntity.code == Api.SUCCESS_CODE) {
        ///将数据保存
        SpUtil.putString(SpKeys.userHead, userInforEntity.data.pic);
        Provider.of<UserInforModel>(context)
            .updateMoney(userInforEntity.data.money);
        Provider.of<UserInforModel>(context)
            .updateGold(userInforEntity.data.gold);

        getImperfect();

        setState(() {});
        _easyRefreshController.finishRefresh();
        return;
      }

      if (userInforEntity.code == Api.ERROR_CODE) {
        ToastUtil.showShortToast(userInforEntity.message);
        _easyRefreshController.finishRefresh();
        return;
      }
    }, (err) {
      ToastUtil.showShortErrToast(err);
      _easyRefreshController.finishRefresh();
    });
  }

  void logOut(UserModel userModel) {
    // SpUtil.clear();
    SpUtil.remove(SpKeys.userToken);
    SpUtil.remove(SpKeys.userPhone);
    SpUtil.remove(SpKeys.userHead);
    userInforEntity = null;
    userModel.updateToken("");
    imperfectEntity = null;
    accountOk = true;
    setState(() {});
  }

  int getIndex(String s) {
    if (s == "进行中") {
      return 1;
    } else if (s == "待评价") {
      return 2;
    } else if (s == "已完成") {
      return 3;
    } else if (s == "已失败") {
      return 4;
    }

    return 0;
  }

  Widget getTs() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(30)),
      child: Column(
        children: <Widget>[
          this.getBottomFunItem("我是推手（团队创始人）", null, msg: ""),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(0)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                this.getTsItem("我是推手", Icons.group),
                this.getTsItem("推手权益", Icons.free_breakfast),
                this.getTsItem("推广统计", Icons.equalizer),
                this.getTsItem("统计收益", Icons.assessment),
              ],
            ),
          )
        ],
      ),
    );
  }

  getTsItem(String s, IconData icon, {String num = ""}) {
    Paint pg = Paint();
    pg.style = PaintingStyle.fill;
    pg.color = Color(0x00000000);

    return InkWell(
      onTap: () {
        int index = getTsIndex(s);

        if (index == 3) {
          ///跳转到 推广赚钱页面
          NavigatorUtils.push(context, Routes.shareTs);
        } else {
          ///跳转到推手
          NavigatorUtils.push(context, "${Routes.ts}?index=$index");
        }
      },
      child: Column(
        children: <Widget>[
          Stack(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(10),
                    right: ScreenUtil().setWidth(10),
                    top: ScreenUtil().setWidth(10)),
                child: Icon(
                  icon,
                  color: Colors.grey[850],
                  size: 30,
                ),
              ),
              Positioned(
                right: 0,
                child: num == ""
                    ? Container()
                    : Container(
                        height: ScreenUtil().setWidth(36),
                        width: ScreenUtil().setWidth(36),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: Colours.appC10, // 底色
                          borderRadius: new BorderRadius.circular(50), // 圆角度
                          //  borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 50)), // 也可控件一边圆角大小
                        ),
                        child: Text(
                          "$num",
                          style: TextStyles.custom(
                              24, Colours.white, Font.PingFangMedium),
                        ),
                      ),
              )
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
            child: Text(
              "$s",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangMedium),
            ),
          )
        ],
      ),
    );
  }

  int getTsIndex(String s) {
    if (s == "我是推手") {
      return 0;
    } else if (s == "推广统计") {
      return 1;
    } else if (s == "统计收益") {
      return 2;
    } else {
      return 3;
    }
  }

  void picadd(String valu) {
    FormData params = FormData.from({"avatar": valu});
    DioManager.getInstance().post(Api.USER_PICADD, params, (json) {
      PicaddEntity entity = PicaddEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast("头像上传:${Api.ERR_NOTHING}");
      }
      if (entity.code == 200) {
        setState(() {
          userInforEntity.data.pic = valu;
        });
      }
    }, (err) {
      ToastUtil.showShortErrToast("头像上传:${Api.ERR_NOTHING}");
    });
  }

  void getImperfect() {
    DioManager.getInstance().get(Api.USER_IMPERFECT, null, (json) {
      imperfectEntity = ImperfectEntity.fromJson(json);
      if (null != imperfectEntity && imperfectEntity.data.isNotEmpty) {
        setState(() {
          accountOk = false;
        });
        return;
      } else {
        setState(() {
          accountOk = true;
        });
      }
    }, (err) {});
  }
}
